package com.zhx.app.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhx.core.common.LoginType;
import com.zhx.core.common.properties.SecurityProperties;
import com.zhx.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理器
 * 和成功处理器同样的逻辑
 * 完成后需要重新注入到config中
 *
 * 可以 实现 AuthenticationFailureHandler
 * 也可以直接继承 spring的默认失败处理逻辑器 SimpleUrlAuthenticationFailureHandler
 *
 * @author zhx
 * @create 2017-11-02 11:34
 **/
@Component("myAuthentionFailedHandler")
public class MyAuthentionFailedHandler extends SimpleUrlAuthenticationFailureHandler {
    private  final static Logger logger = LoggerFactory.getLogger(MyAuthentionFailedHandler.class);

    //spring 启动的时候自动注册的一个mapper 可以转换类
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.info("登录失败!");

        //如果配置的登陆项是需要json返回的情况
        if(securityProperties.getBrowser().getLoginType().equals(LoginType.JSON)){
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            httpServletResponse.setContentType("application/json,charset=UTF-8");
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Result.error(e.getMessage())));
        }

        //如果配置的项是需要直接跳转就是spring默认的处理方式
        if(securityProperties.getBrowser().getLoginType().equals(LoginType.REDIECT)){
            super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
        }


    }
}
